﻿// <copyright file="CustomVisualTreeHelper.cs" company="Ucaya">
// </copyright>
// <author>Ucaya</author>

namespace KinectExtensions.Helpers
{
    #region

    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Media;

    #endregion

    /// <summary>
    ///   TODO: Update summary.
    /// </summary>
    public static class CustomVisualTreeHelper
    {
        #region Public Methods

        public static IEnumerable<FrameworkElement> Ancestors(this FrameworkElement element)
        {
            FrameworkElement parent = element;
            while (parent != null)
            {
                parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
                if (parent != null)
                {
                    yield return parent;
                }
            }
        }

        /// <summary>
        ///   The get descendant bounds.
        /// </summary>
        /// <param name = "source">
        ///   The source.
        /// </param>
        /// <returns>
        /// </returns>
        public static Rect GetHitableDescendantBounds(FrameworkElement source)
        {
            if (source.Visibility == Visibility.Collapsed)
            {
                return Rect.Empty;
            }

            Rect rect = VisualTreeHelper.GetContentBounds(source);
            int childrenCount = VisualTreeHelper.GetChildrenCount(source);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(source, i) as FrameworkElement;

                if (child == null || child.Visibility == Visibility.Collapsed || !child.IsHitTestVisible)
                {
                    continue;
                }

                Rect childBounds = GetHitableDescendantBounds(child);
                Rect localBounds = child.TransformToAncestor(source).TransformBounds(childBounds);
                rect.Union(localBounds);
            }

            return rect;
        }

        #endregion
    }
}